/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package kcollgen;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.logging.FileHandler;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Pierre
 */
public class KCollGenerator {
    
    static final Logger logger = Logger.getLogger("logger");
    
    
    
    Boolean createOrphanCollection = true;
    public static final String TEMP_FILE_NAME = ".manga_save";
    
    String kindleBaseDir = Utilities.getDefaultMountingPoint();
    String systemPrefix = "/mnt/us/";
    ArrayList<String> parentDirs = new ArrayList<String>(){{
        add("pictures");
        add("documents");
    }};
    ArrayList<String> fileExtensions = new ArrayList<String>(){{
       add("cbz"); 
       add("pdf");
    }};

    public KCollGenerator(String kindlebaseDir) {
        this.kindleBaseDir = kindlebaseDir;
    }

    public KCollGenerator(String kindlebaseDir, ArrayList<String> fileExtensions, 
            ArrayList<String> parentDirs, Boolean createOrphanCollection) {
        this.kindleBaseDir = kindlebaseDir;
        this.parentDirs = parentDirs;
        this.fileExtensions = fileExtensions;
        this.createOrphanCollection = createOrphanCollection;
    }
    
    
    
    public Boolean checkBaseDir(){
        if((new File(kindleBaseDir).isDirectory()) == false)
            return false;
        else{
            for(String s : parentDirs)
                if(!(new File(kindleBaseDir + s).isDirectory()))
                    return false;
        }
        return true;
    }
    
    /**
     * Passer private et utiliser une methode static 
     */
    public void createColObjectModel() throws IOException{
        
        int otfNum = 0;
        CollectionJson res = new CollectionJson();
        
        Handler handler = new FileHandler("Ylog.html");
        handler.setFormatter(new Yformatter());
        logger.addHandler(handler);
        
        Boolean orphanCollectionCreated = false;
        
        /* On verifie le point de montage */
        if(checkBaseDir() == false){
            logger.log(Level.SEVERE, "Error : Kindle not plugged in, or {0} is not the Kindle mounting point", kindleBaseDir);
            System.exit(0);
        }
        
        for(String parentDir : parentDirs){
            String fullParentDir = kindleBaseDir + parentDir + "/";
                for(String parentSubDir : new File(fullParentDir).list()){
                    String fullParentSubDir = fullParentDir + parentSubDir;
                    if(new File(fullParentSubDir).isDirectory() == true){
                        fullParentSubDir += "/";
                        res.addCol(parentSubDir);
                        
                        String[] fullParentSubDirContents = new File(fullParentSubDir).list();
                        
                        for(String f : fullParentSubDirContents){
                            for(String extension : fileExtensions)
                                if(f.endsWith(extension)){
                                    String sha1String = systemPrefix + parentDir +
                                        "/" + parentSubDir + "/" + f;
                                    logger.log(Level.INFO, "Adding \"{0}\" to collection \"{1}\"\n",
                                            new Object[]{f, parentSubDir});
                                    res.addSha1ToCol(parentSubDir, Sha1.sha1(sha1String));
                                }
                        }
                    }    
                    else{
                        if(createOrphanCollection)
                            for(String extension : fileExtensions)
                                if(parentSubDir.endsWith(extension)){
                                    if(!orphanCollectionCreated){
                                        res.addCol("Orphan Files");
                                        orphanCollectionCreated = true;
                                    }
                                    String sha1String = systemPrefix + parentDir +
                                            "/" + parentSubDir;
                                    logger.log(Level.INFO, "DEBUG : {0}", sha1String);
                                    res.addSha1ToCol("Orphan Files", Sha1.sha1(sha1String));
                                    logger.log(Level.INFO,"Adding {0}" + " to orphan "
                                            + "collection", parentSubDir);

                            }
                        
                    }
                    
                }
        }
        
        logger.log(Level.INFO, "Scanning for orphan temporary files ...");
        
        for(String parentDir : parentDirs){
            String fullParentDir = kindleBaseDir + parentDir + "/";
            for(String parentSubDir : new File(fullParentDir).list()){
                String fullParentSubDir = fullParentDir + parentSubDir;
                if(new File(fullParentSubDir).isDirectory() == true){
                    fullParentSubDir += "/";
                    for(String f : new File(fullParentSubDir).list())
                        if(f.endsWith(TEMP_FILE_NAME)){
                            String baseName = f.substring(0, f.length()-TEMP_FILE_NAME.length());
                            Boolean ok = false;
                            for(String f2 : new File(fullParentSubDir).list()){
                                if(f2.startsWith(baseName) && !f2.equals(f)){
                                    ok = true;
                                    break;
                                }
                            }
                            if(!ok){
                                logger.log(Level.INFO, "Deleting orphan temporary file : {0}{1}",
                                        new Object[]{fullParentSubDir, f});
                                new File(fullParentSubDir + f).delete();
                                otfNum++;
                            }
                        }
                    
                }
            }
        }
        
        logger.log(Level.INFO, "Creating backup file : {0}/system/collections.json.bak", 
                kindleBaseDir);
        new File(kindleBaseDir + "/system/collections.json").renameTo
                (new File(kindleBaseDir + "/system/collections.json.bak"));
        
        logger.log(Level.INFO, "Writing collection file : {0}/system/collections.json", kindleBaseDir);
        FileWriter fw = new FileWriter(kindleBaseDir + "/system/collections.json", false);
        fw.write(res.getKindleOutputBuffer());
        
        logger.log(Level.INFO, "DONE.");
        
        int nbColCreated = res.collections.size();
        logger.log(Level.INFO, "{0} collection(s) created :", nbColCreated);
        for(int i=0; i<nbColCreated; i++)
        {
           logger.log(Level.INFO, "  - {0}", res.collections.get(i).colName);
        }
        logger.log(Level.INFO, "{0} orphan temporary file(s) deleted", otfNum);
        
        fw.flush(); fw.close();
        
        logger.log(Level.INFO, "Please reboot your Kindle (Settings -> Menu -> Restart)");
        handler.flush(); handler.close();
        
        
    }
    
}